package com.monkeygroup.mygoplus.view.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.common.DefinedView.MyDialog;
import com.monkeygroup.mygoplus.common.utils.VilidateUtil;
import com.monkeygroup.mygoplus.ecchat.common.CCPAppManager;
import com.monkeygroup.mygoplus.ecchat.common.utils.ToastUtil;
import com.monkeygroup.mygoplus.ecchat.storage.ContactSqlManager;
import com.monkeygroup.mygoplus.ecchat.storage.GroupSqlManager;
import com.monkeygroup.mygoplus.ecchat.ui.SDKCoreHelper;
import com.monkeygroup.mygoplus.ecchat.ui.contact.ECContacts;
import com.monkeygroup.mygoplus.ecchat.ui.contact.SearchFriendsActivity;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactMemberDTO;
import com.monkeygroup.mygoplus.view.home.activity.MainActivity;
import com.monkeygroup.mygoplus.ecchat.ui.chatting.ChattingActivity;
import com.monkeygroup.mygoplus.ecchat.ui.chatting.ChattingFragment;
import com.monkeygroup.mygoplus.ecchat.ui.contact.AddFriendMainActivity;
import com.monkeygroup.mygoplus.ecchat.ui.contact.NewFriendApplyActivity;
import com.monkeygroup.mygoplus.ecchat.ui.contact.adapter.ContactExpandableListAdapter;
import com.monkeygroup.mygoplus.ecchat.ui.contact.entity.ContactDTO;
import com.monkeygroup.mygoplus.http.HttpModel;
import com.monkeygroup.mygoplus.http.RequestUrl;
import com.yuntongxun.ecsdk.ECError;
import com.yuntongxun.ecsdk.ECGroupManager;
import com.yuntongxun.ecsdk.ECVoIPCallManager;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.ecsdk.im.ECGroup;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/25.
 */
public class ContactFragment extends Fragment implements View.OnClickListener {
    private View mView;
    private TextView info_nickname, info_userid, apply_num_tip;
    private MainActivity mParent = null;
    private ExpandableListView myContactListView;
    private ContactExpandableListAdapter adapter;
    private List<ContactDTO> contactDataList = new ArrayList<>();
    private Map<String, ContactMemberDTO> concernList = new HashMap<>();
    private MyDialog infoDialog = null, exchangeDialog = null;
    private final String NEW_FRIENDS = "new_friends", MUTUAL_FRIENDS = "mutual_friends";
    private final String NORMAL = "normal", NEW_FRIEND = "newFriends", FAVORITE = "favorite", OFFICIAL = "officical";
    private final String TAG = "ContactFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.fragment_chat_contact, container, false);
            mParent = (MainActivity) getActivity();
            initView();
            initListener();
            initData();
        }
        return mView;
    }

    private void initView() {
        myContactListView = (ExpandableListView) mView.findViewById(R.id.myContactListView);
        refreshMyInfo();
    }

    private void initListener() {
        mView.findViewById(R.id.layout_back).setOnClickListener(this);
        mView.findViewById(R.id.add_friend).setOnClickListener(this);
        mView.findViewById(R.id.more_event).setOnClickListener(this);
        mView.findViewById(R.id.tab_recommend).setOnClickListener(this);
        mView.findViewById(R.id.tab_conversation_list).setOnClickListener(this);
        mView.findViewById(R.id.layout_my_info).setOnClickListener(this);
        mView.findViewById(R.id.layout_new_apply).setOnClickListener(this);
        mView.findViewById(R.id.layout_search).setOnClickListener(this);

    }

    private void initData() {
        initGroupData();
        initAdapter();

        getGroupList();
        doFriends();
    }

    private void initAdapter() {
        adapter = new ContactExpandableListAdapter(getActivity(), contactDataList);
        myContactListView.setAdapter(adapter);
        myContactListView.setGroupIndicator(null);
        myContactListView.setVerticalScrollBarEnabled(false);

        myContactListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {

                ImageView icon = (ImageView) v.findViewById(R.id.groupIcon);
                if (icon.getTag().equals(0)) {
                    icon.setImageResource(R.drawable.chat_contact_show);
                    icon.setTag(1);
                } else if (icon.getTag().equals(1)) {
                    icon.setImageResource(R.drawable.chat_contact_hide);
                    icon.setTag(0);
                }
                return false;
            }
        });

        myContactListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, final View v, int groupPosition, int childPosition, long id) {
                final ContactMemberDTO memberDTO = adapter.getChild(groupPosition, childPosition);
                final String userid = memberDTO.getId();
                String type = memberDTO.getType();

                /**列表是群組**/
                if (type != null && type.equals("ecgroup")) {
                    Intent enterIntent = new Intent(getActivity(), ChattingActivity.class);
                    enterIntent.putExtra(ChattingFragment.RECIPIENTS, userid);
                    enterIntent.putExtra(ChattingFragment.CONTACT_USER, adapter.getChild(groupPosition, childPosition).getName());
                    enterIntent.putExtra(ChattingFragment.CUSTOMER_SERVICE, false);
                    startActivity(enterIntent);

                    return false;
                }

                boolean isFavorite;
                if (concernList.containsKey(userid)) {
                    isFavorite = true;
                } else {
                    isFavorite = false;
                }
                exchangeDialog = new MyDialog(getActivity(), R.style.MyDialogTheme, isFavorite, new MyDialog.OnFriendExchangeListener() {
                    @Override
                    public void doMessage() {
                        exchangeDialog.dismiss();

                        Intent intent = new Intent(getActivity(), ChattingActivity.class);
                        intent.putExtra(ChattingFragment.RECIPIENTS, userid);
                        if (MyGoApplication.getContacts().containsKey(userid)) {
                            String remark = MyGoApplication.getContacts().get(userid).getRemark();
                            if (remark != null && !remark.equals("")) {
                                intent.putExtra(ChattingFragment.CONTACT_USER, remark);
                            } else {
                                intent.putExtra(ChattingFragment.CONTACT_USER, memberDTO.getName());
                            }
                        } else {
                            intent.putExtra(ChattingFragment.CONTACT_USER, memberDTO.getName());
                        }

                        startActivity(intent);
                    }

                    @Override
                    public void doCall() {
                        exchangeDialog.dismiss();

                        handleVoiceCall(userid);
                    }

                    @Override
                    public void doVideo() {
                        exchangeDialog.dismiss();

                        handleVideoCall(userid);
                    }

                    @Override
                    public void doFavorite(ImageView view) {
                        if (concernList.containsKey(userid)) {
                            doCancelConcern(userid, view);
                        } else {
                            doConcern(userid, view);
                        }
                    }
                });

                return false;
            }
        });
    }

    private void refreshMyInfo() {
        info_nickname = (TextView) mView.findViewById(R.id.info_nickname);
        info_nickname.setText(MyGoApplication.myNickname);
        info_userid = (TextView) mView.findViewById(R.id.info_userid);
        info_userid.setText(MyGoApplication.myECUserid);
        apply_num_tip = (TextView) mView.findViewById(R.id.apply_num_tip);
        if (MyGoApplication.applyNum > 0) {
            apply_num_tip.setVisibility(View.VISIBLE);
            apply_num_tip.setText(MyGoApplication.applyNum);
        } else {
            apply_num_tip.setVisibility(View.GONE);
        }
    }

    /**
     * 临时搭建数据
     **/
    private void initGroupData() {
        contactDataList.add(new ContactDTO("新朋友", "10001", "1", 0, null));
        contactDataList.add(new ContactDTO("我的最愛", "10002", "2", 0, null));
        contactDataList.add(new ContactDTO("官方帳號", "10003", "3", 0, null));
        contactDataList.add(new ContactDTO("群组", "10004", "4", 0, null));
        contactDataList.add(new ContactDTO("好友列表", "10005", "5", 0, null));
    }

    //獲取群組列表
    private void getGroupList() {
        ECGroupManager groupManager = SDKCoreHelper.getECGroupManager();
        // 调用查询个人加入的群组接口，设置结果回调
        //Target.Group是群组，Target.Discussion是讨论组
        groupManager.queryOwnGroups(ECGroupManager.Target.DISCUSSION, new ECGroupManager.OnQueryOwnGroupsListener() {
            @Override
            public void onQueryOwnGroupsComplete(ECError ecError, List<ECGroup> list) {
                if (SdkErrorCode.REQUEST_SUCCESS == ecError.errorCode) {
                    // 請求成功，不保存在服務器
                    GroupSqlManager.delALLDisGroup();
                    List<ContactMemberDTO> groupList = new ArrayList<>();
                    if (list != null && list.size() > 0) {
                        for (ECGroup group : list) {
                            ContactMemberDTO item = new ContactMemberDTO();
                            item.setName(group.getName());
                            item.setId(group.getGroupId());
                            item.setType("ecgroup");
                            groupList.add(item);
                        }
                        GroupSqlManager.insertDisGroupInfos(list, 1);
                    }
                    contactDataList.get(3).setMemberList(groupList);
                    adapter.notifyDataSetChanged();
                } else {
                    ToastUtil.showMessage("獲取群組信息失敗！");
                }
            }
        });
    }

    private void setFriendsData(List<Map<String, String>> list, String type) {
        List<ContactMemberDTO> friendList = new ArrayList<>();
        for (Map<String, String> item : list) {
            ContactMemberDTO memberDTO = new ContactMemberDTO();
            if (item.get("username") != null && !item.get("username").equals("")) {
                memberDTO.setName((String) item.get("username"));
            } else if (item.get("userID") != null && !item.get("userID").equals("")) {
                memberDTO.setName((String) item.get("userID"));
            } else {
                memberDTO.setName((String) item.get("mobile"));
            }

            memberDTO.setId((String) item.get("mobile"));
            memberDTO.setHeadUrl((String) item.get("headIcon"));
            memberDTO.setStatus(item.get("status"));
            memberDTO.setEmail(item.get("email"));
            memberDTO.setIsOffice(item.get("isOffice"));
            memberDTO.setNotification(item.get("notification"));
            memberDTO.setRemark(item.get("remark"));
            friendList.add(memberDTO);
        }

        if (type.equals(NEW_FRIEND)) {
            contactDataList.get(0).setMemberList(friendList);
        } else if (type.equals(FAVORITE)) {
            contactDataList.get(1).setMemberList(friendList);

            Map<String, ContactMemberDTO> friends = new HashMap<>();
            for (ContactMemberDTO memberDTO : friendList) {
                friends.put(memberDTO.getId(), memberDTO);
            }
            MyGoApplication.setConcernList(friends);
        } else if (type.equals(OFFICIAL)) {
            contactDataList.get(2).setMemberList(friendList);
        } else if (type.equals(NORMAL)) {
            contactDataList.get(4).setMemberList(friendList);
            adapter.notifyDataSetChanged();

            Map<String, ContactMemberDTO> friends = new HashMap<>();
            for (ContactMemberDTO memberDTO : friendList) {
                friends.put(memberDTO.getId(), memberDTO);
            }
            MyGoApplication.setContacts(friends);
        }
        adapter.notifyDataSetChanged();
    }

    private void setOfficalData(List<Map<String, Object>> list) {
        List<ContactMemberDTO> friendList = new ArrayList<>();
        for (Map<String, Object> item : list) {
            ContactMemberDTO memberDTO = new ContactMemberDTO();
            if (item.get("username") != null && !item.get("username").equals("")) {
                memberDTO.setName((String) item.get("username"));
            } else if (item.get("userID") != null && !item.get("userID").equals("")) {
                memberDTO.setName((String) item.get("userID"));
            } else {
                memberDTO.setName((String) item.get("mobile"));
            }

            memberDTO.setId((String) item.get("mobile"));
            memberDTO.setHeadUrl((String) item.get("headIcon"));
            friendList.add(memberDTO);
        }

        contactDataList.get(2).setMemberList(friendList);
        adapter.notifyDataSetChanged();
    }

    private void setConcernData(List<Map<String, String>> list) {
        List<ContactMemberDTO> friendList = new ArrayList<>();
        for (Map<String, String> item : list) {
            ContactMemberDTO memberDTO = new ContactMemberDTO();
            if (item.get("userID") != null && !item.get("userID").equals("")) {
                memberDTO.setName(item.get("userID"));
            } else {
                memberDTO.setName(item.get("mobile"));
            }
            memberDTO.setId(item.get("mobile"));

            concernList.put(memberDTO.getId(), memberDTO);
            friendList.add(memberDTO);
        }

        contactDataList.get(1).setMemberList(friendList);
        adapter.notifyDataSetChanged();

        Map<String, ContactMemberDTO> friends = new HashMap<>();
        for (ContactMemberDTO memberDTO : friendList) {
            friends.put(memberDTO.getId(), memberDTO);
        }
        MyGoApplication.setConcernList(friends);
    }

    private void doFriends() {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        String requestUrl;
        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);
        requestUrl = RequestUrl.baseUrl + RequestUrl.requestAllContact;
        HttpModel httpModel = new HttpModel(requestUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, Object> map = (Map) data;
                    Iterator<Map.Entry<String, Object>> entries = map.entrySet().iterator();

                    while (entries.hasNext()) {
                        Map.Entry<String, Object> entry = entries.next();
                        System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

                        List<Map<String, String>> list = (ArrayList) entry.getValue();
                        setFriendsData(list, entry.getKey());
                    }

//                    List<Map<String, String>> list = (ArrayList) map.get("friends");
//                    setFriendsData(list, type);

                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private void doOfficalList() {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestOfficialList;
        HttpModel httpModel = new HttpModel(requestUrl, getOfficalParams(), new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, Object> map = (Map) data;
                    List<Map<String, Object>> list = (ArrayList) map.get("friends");
                    setOfficalData(list);

                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private Map<String, String> getOfficalParams() {
        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);
        params.put("pages", "1");
        params.put("size", "20");

        return params;
    }

    private void doConcernList() {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestConcernList;
        HttpModel httpModel = new HttpModel(requestUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, Object> map = (Map) data;
                    List<Map<String, String>> list = (ArrayList) map.get("list");
                    setConcernData(list);
                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private void doConcern(String userid, final ImageView imageView) {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);
        params.put("concernMobile", userid);

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestConcernUrl;
        HttpModel httpModel = new HttpModel(requestUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, String> map = (Map) data;
                    ToastUtil.showMessage(map.get("message"));
                    imageView.setImageResource(R.drawable.bt_chat_favorite_ok);
                    doConcernList();
                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private void doCancelConcern(String userid, final ImageView imageView) {
        if (MyGoApplication.myECUserid.equals(""))
            return;

        Map<String, String> params = new HashMap<>();
        params.put("mobile", MyGoApplication.myECUserid);
        params.put("concernMobile", userid);

        String requestUrl = RequestUrl.baseUrl + RequestUrl.requestCancelConcern;
        HttpModel httpModel = new HttpModel(requestUrl, params, new HttpModel.SimpleOnHttpRequestListener() {
            @Override
            public void onRequestFinished(int resultCode, String resultMsg, Object data) {
                if (VilidateUtil.isSuccess(resultCode)) {
                    Map<String, String> map = (Map) data;
                    ToastUtil.showMessage(map.get("message"));
                    imageView.setImageResource(R.drawable.bt_chat_favorite_invalid);
                    doConcernList();
                } else {
                    Toast.makeText(getActivity(), resultMsg, Toast.LENGTH_SHORT).show();
                }
            }
        }, true);

        httpModel.startRequest();
    }

    private void showFragment(String tag) {
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        Fragment fragment = fragmentManager.findFragmentByTag(tag);

        mParent.setFragment(fragment);
    }

    private void handleVoiceCall(String userid) {
        ECContacts contact = ContactSqlManager.getContact(userid);
        if (contact == null) {
            return;
        }
        CCPAppManager.callVoIPAction(getActivity(), ECVoIPCallManager.CallType.VOICE,
                contact.getNickname(), contact.getContactid(), false);

    }

    private void handleVideoCall(String userid) {
        ECContacts contact = ContactSqlManager.getContact(userid);

        if (contact == null) {
            return;
        }
        CCPAppManager.callVoIPAction(getActivity(), ECVoIPCallManager.CallType.VIDEO,
                contact.getNickname(), contact.getContactid(), false);

    }

    /**
     * 請求聯繫人需要加聯繫人變化的限制條件
     **/
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            refreshMyInfo();
            getGroupList();
            doFriends();
        }
    }


    /**
     * 請求聯繫人需要加聯繫人變化的限制條件
     **/
    @Override
    public void onResume() {
        super.onResume();

        refreshMyInfo();
        getGroupList();
        doFriends();
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.layout_back:
            case R.id.tab_conversation_list:
                mParent.setChatFocusIndex(0);
                showFragment("mConversationFragment");
                break;
            case R.id.tab_recommend:
                mParent.setChatFocusIndex(2);
                showFragment("mRecommendFragment");
                break;
            case R.id.add_friend:
                intent.setClass(getActivity(), AddFriendMainActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_my_info:
                infoDialog = new MyDialog(getActivity(), R.style.MyDialogTheme, null, new MyDialog.OnUserDetailListener() {
                    @Override
                    public void doUserDetail(String userid) {
                        infoDialog.dismiss();
                    }
                });
                infoDialog.show();
                break;
            case R.id.layout_new_apply:
                intent.setClass(getActivity(), NewFriendApplyActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_search:
                intent.setClass(getActivity(), SearchFriendsActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

}
